// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package file

import (
	"audio-server/internal/model"
	"audio-server/internal/sqlutil"
	"audio-server/internal/svc"
	"audio-server/internal/types"
	"context"
	"database/sql"
	"encoding/json"
	"path/filepath"
	"strings"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFileSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileSaveLogic {
	return &FileSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FileSaveLogic) FileSave(req *types.MultipleFileSaveReq) (resp bool, err error) {
	//  先查询是否存在该文件
	id := sqlutil.GetUserId(l.ctx)
	names := req.TagNames
	list := req.List

	var jsonStr string
	if len(names) > 0 {
		jsonData, jsonErr := json.MarshalIndent(names, "", "  ")
		if jsonErr != nil {
			return false, err
		}
		jsonStr = string(jsonData)
	}
	for _, file := range list {
		ext := filepath.Ext(file.Name)
		parentId := file.ParentId
		fileModel := model.NewSysFileModel(l.svcCtx.Conn)
		oldFile, _ := fileModel.FindByName(l.ctx, id, file.Name)
		newFile := model.SysFile{
			ExtendName: sql.NullString{String: strings.ToLower(strings.TrimPrefix(ext, ".")), Valid: true},
			Name:       file.Name,
			ParentId:   parentId,
			Size:       int64(file.Size),
			Src:        sql.NullString{String: file.Src, Valid: true},
			Tags:       sql.NullString{String: jsonStr, Valid: true},
			UpdateTime: time.Now(),
			UserId:     sql.NullInt64{Int64: id, Valid: true},
			Path:       "/" + file.Name,
		}
		if parentId > 0 {
			parentFile, err := fileModel.FindOne(l.ctx, parentId)
			if err == nil {
				newFile.Path = parentFile.Path + "/" + file.Name
			}
		}
		if oldFile != nil {
			newFile.FileId = oldFile.FileId
			err = fileModel.Update(l.ctx, &newFile)
			if err != nil {
				return false, err
			}
		} else {
			_, updateErr := fileModel.Insert(l.ctx, &newFile)
			if updateErr != nil {
				return false, updateErr
			}
		}
	}

	return true, err

}
